package teaching.api;

import cn.hutool.core.io.FileUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import teaching.pojo.Course;
import teaching.pojo.CourseStudent;
import teaching.service.CourseService;
import teaching.util.Response;
import teaching.util.ResponseResult;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;


/**
 * Author:20201002983_郑雨蓓
 * Date: 2024/3/5
 * Description:url:http://localhost:8080/course
 */
@RestController
@RequestMapping("/course")
@Api(tags = "课程相关接口")
public class CourseAPI {
    @Resource
    private CourseService courseService;
    //    public final static Logger log =
//            LoggerFactory.getLogger(CourseAPI.class);
    public static final String FILE_PATH = "D:\\ProgramData\\JavaProject\\teaching\\files";

    @PostMapping("/upload")
    public ResponseResult<Object> fileUpload(MultipartFile file) {

        try {
            if (file == null) {
                return Response.createFailResp("File is null");
            }
            //eg:xxx.jpg
            String originalFilename = file.getOriginalFilename();//文件原始名称
            File parentFile = new File(FILE_PATH);
            if (!parentFile.exists()) {
                parentFile.mkdirs();//如果文件目录不存在则创建
            }
            File saveFile = new File(FILE_PATH + File.separator + originalFilename);
            file.transferTo(saveFile);
            String url = "http://localhost:8080/course/download/" + originalFilename;
            return Response.createOkResp(url);

        } catch (IOException e) {
            e.printStackTrace();
            return Response.createFailResp(e.getMessage());
        }
    }

    @ApiOperation("下载文件")
    @GetMapping("/download/{filename}")
    public void download(@PathVariable String filename, HttpServletResponse response) {
        try {
            String filePath = FILE_PATH + File.separator + filename;
            if (!FileUtil.exist(filePath)) {
                System.out.println("文件不存在");
                return;
            }
            byte[] bytes = FileUtil.readBytes(filePath);
            ServletOutputStream outputStream = response.getOutputStream();
            outputStream.write(bytes);//文件的字节读数组
            outputStream.flush();
            outputStream.close();//关闭文件流
            //文件的链接，额就是下载地址，后台提供的

        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    //教师端
    @GetMapping("/courseList/{userid}")//教师端课程信息
    public ResponseResult<List<Course>> getCourse(@PathVariable("userid") Long userid) {
        List<Course> courseList = courseService.list(userid);
        return Response.createOkResp(courseList);
    }

    @PostMapping("/creatCourse")
    @ApiOperation("添加课程信息")
    public ResponseResult<Object> upload(Course newCourse) {
        try {
            System.out.println(newCourse.toString());
            if (newCourse.getCourseName() != null && !newCourse.getCourseName().equals("")) {
                int num = courseService.addCourse(newCourse);
                System.out.println("影响行数：" + num);
                //返回文件的下载地址
                return Response.createOkResp("新建成功");
            } else {
                return Response.createFailResp("新建失败");
            }
        } catch (IllegalStateException e) {
            e.printStackTrace();
            return Response.createFailResp("新建失败: " + e.getMessage());
        }
    }

    @PutMapping("/updateCourse")
    public ResponseResult<Object> updateCourse(@RequestBody Course course) {
        System.out.println(course);
        int num = courseService.update(course);
        System.out.println("影响行数：" + num);
        return Response.createMsgResp("修改成功");
    }

    @ApiOperation("删除课程")
    @DeleteMapping("/delete/{cid}")
    public ResponseResult<Object> delete(@PathVariable("cid") Long cid) {
        int num = courseService.delete(cid);
        System.out.println("cid" + cid + "影响行数:" + num);
        return Response.createOkResp("删除成功");
    }

    //学生端
    @GetMapping("/studentCourse/{student_id}")
    public ResponseResult<List<Course>> getCourses(@PathVariable("student_id") Long student_id) {
        List<Course> courseList = courseService.studentCourse(student_id);
        return Response.createOkResp(courseList);
    }

    //批量添加课程学生
    @PostMapping("/addStudentsToCourse")
    public ResponseResult<Object> addStudentsToCourse(@RequestBody CourseStudent courseStudent) {
        courseService.addMulCourseStudent(courseStudent);
        return Response.createOkResp("添加成功");
    }
}
